<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 论坛点赞接口
 */
class Forumzan extends Api
{
    protected $noNeedRight = ['*'];

    //点赞
    public function add()
    {
        $forum_id = input('forum_id',0);
        if (empty($forum_id)) {
            $this->error('缺少参数论坛id');
        }
        $data = [
            'user_id' => $this->auth->id,
            'forum_id' => $forum_id,
        ];

        $collect = new \app\api\model\forum\ForumZan();

        $info = \app\api\model\forum\ForumZan::where(['forum_id'=>$forum_id, 'user_id' => $this->auth->id])->find();
        if (empty($info)){
            $res = $collect->save($data);
            if ($res){
                \app\api\model\forum\Forum::where(['forum_id'=>$forum_id])->setInc('zan_num',1);

            }
            $this->success('点赞成功',$res);
        } else {
            $this->error('点赞失败');
        }
    }

    //删除
    public function delete()
    {
        $forum_id = input('forum_id',0);
        if (empty($forum_id)) {
            $this->error('缺少参数论坛id');
        }

        $info = \app\api\model\forum\ForumZan::where(['forum_id'=>$forum_id, 'user_id' => $this->auth->id])->find();

        if (!empty($info)){
            $res = $info->delete();
            if ($res){
                \app\api\model\forum\Forum::where(['forum_id'=>$forum_id])->setDec('zan_num',1);
            }
            $this->success('取消成功',$res);
        } else {
            $this->error('取消失败');
        }
    }

    //是否点赞
    public function iszan()
    {
        $forum_id = input('forum_id',0);
        if (empty($forum_id)) {
            $this->error('缺少参数论坛id');
        }

        $info = \app\api\model\forum\ForumZan::where(['forum_id'=>$forum_id, 'user_id' => $this->auth->id])->find();

        if (!empty($info)) {
            $this->success('',1);
        } else {
            $this->success('',0);
        }
    }

    //点赞列表
    public function page()
    {
        $keyword = input('keyword','');

        $where = ['fz.user_id'=>$this->auth->id];

        if ($keyword){
            $where['f.forum_name|f.forum_content'] = ['like', '%' . $keyword . '%'];
        }

        $list = \app\api\model\forum\ForumZan::alias('fz')
            ->join('user u', 'u.id=fz.user_id', 'LEFT')
            ->join('forum f', 'f.forum_id=fz.forum_id', 'LEFT')
            ->field('f.*,u.nickname,u.avatar')
            ->where($where)
            ->order('fz.createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);
        $this->success('请求成功',$list);
    }
}